<template>
  <div>
    <div style="display: flex; padding: 10px 0px; align-items: center">
      <div style="display: flex; justify-content: end">
        <ht-upload
          v-if="busKey && busField && showUpload"
          ref="fileUpload"
          class="upload-demo"
          :dbKey="dbKey"
          :busField="busField"
          :busKey="busKey + ''"
          :busType="busType"
          :ftpKey="ftpKey"
          :showFileList="false"
          style="height: 0px"
          :beforeUpload="commonBeforeUpload"
          :on-success="afterUpload"
        >
          <a-button
            type="primary"
            id="fileUploadId"
            style="width: 80px; margin-right: 15px"
            :size="btnSize"
            v-show="showUpload"
            >上传</a-button
          >
        </ht-upload>
        <a-button @click="downloadFile()" v-show="showDown" style="width: 80px; margin-right: 15px" :size="btnSize"
          >下载</a-button
        >
        <a-button
          @click="deleteFile()"
          style="width: 80px; margin-right: 15px; color: red"
          :size="btnSize"
          v-show="showDelete"
          >删除</a-button
        >
        <a-button @click="fetchAttach()" style="width: 80px; margin-right: 15px" :size="btnSize" v-show="showDelete"
          >刷新</a-button
        >
      </div>
      <div>
        <span v-if="tips" style="margin-left: 15px; color: red">
          {{ tips }}
        </span>
      </div>
    </div>
    <div class="section-table">
      <a-table
        class="hte-table-content"
        :columns="attachColums"
        :data-source="attachList"
        :pagination="false"
        size="middle"
        rowKey="id"
        bordered
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange3 }"
      >
        <template slot="fileName" slot-scope="text, record">
          <template v-if="showDown">
            <a @click="showAttach(record)">{{ record.fileName }}</a>
          </template>
          <template v-else>{{ record.fileName }}</template>
        </template>
        <template slot="size" slot-scope="text">
          {{ formatFileSize(text) }}
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getAction, previewAttach } from '@/api/manage'
import { Modal } from 'ant-design-vue'
import { endWith, formatFileSize } from '@/utils/common.js'
export default {
  props: {
    busKey: {
      type: String,
      default: '',
    },
    busField: {
      type: String,
      default: '',
    },
    busType: {
      type: String,
      default: '',
    },
    showUpload: {
      type: Boolean,
      default: true,
    },
    showDelete: {
      type: Boolean,
      default: true,
    },
    showDown: {
      type: Boolean,
      default: true,
    },
    zipFileName: {
      type: String,
      default: null,
    },
    dbKey: {
      type: String,
      default: 'Trd',
    },
    ftpKey: {
      type: String,
      default: 'ftp',
    },
    tips: {
      type: String,
      default: null,
    },
    btnSize: {
      type: String,
      default: 'default',
    },
    templateFiles: {},
    beforeUpload: {
      type: Function,
      default: () => {return true;},
    },
  },
  data() {
    return {
      attachList: [],
      urls: {
        getAttachs: '/tp/attach/getAttaches',
        downLoadBatchWithFileName: '/common/downLoadBatchWithFileName',
        fileDelete: '/common/deleteBatch',
      },
      attachColums: [
        {
          title: '附件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'fileName' },
        },
        {
          title: '附件大小',
          dataIndex: 'size',
          key: 'size',
          width: '100px',
          scopedSlots: { customRender: 'size' },
        },
        {
          title: '上传时间',
          dataIndex: 'createTime',
          width: '180px',
          key: 'createTime',
        },
        {
          title: '上传者',
          dataIndex: 'uploaderName',
          width: '100px',
          key: 'uploaderName',
        },
      ],
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  computed: {
    _busKey() {
      return this.busKey
    },
  },
  methods: {
    formatFileSize,
    fetchAttach() {
      if (this.busKey) {
        getAction(
          this.urls.getAttachs + '?busField=' + this.busField + '&busKey=' + this.busKey + '&busType=' + this.busType
        ).then((res) => {
          if (res.code == '1') {
            this.attachList = res.data
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    getAttachs() {
      return this.attachList
    },
    onSelectChange3(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    uploadFile() {
      document.getElementById('fileUploadId').click()
    },
    commonBeforeUpload(file) {
      console.info(this.$refs.fileUpload)
      const before = this.beforeUpload(file)
      if (before) {
        return true
      }
      return false
    },
    afterUpload(response, file, fileList) {
      this.fetchAttach()
      this.$emit('afterUpload', response, file, fileList)
    },
    downloadFile() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning('请选择要下载的文件')
        return
      }
      var ids = this.selectedRowKeys.join(',')
      this.doDownLoadBatch(ids)
    },
    deleteFile() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning('请选择要删除的文件')
        return
      }
      var currUser = Vue.ls.get(USER_INFO).username
      var fileNames = []
      this.selectedRows.forEach((f) => {
        if (f.uploader != currUser) {
          fileNames.push(f.fileName)
        }
      })
      if (fileNames.length > 0) {
        this.$message.warning('附件【' + fileNames.join(', ') + '】不是您上传的文件，不可删除')
        return
      }
      const that = this
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除选中的文件, 是否继续?',
        onOk: function () {
          var ids = that.selectedRowKeys.join(',')
          getAction(that.urls.fileDelete, { attachIds: ids }).then((res) => {
            if (res.code == 1) {
              that.$message.success('操作成功')
              that.$emit('afterDel', that.selectedRows)
              that.fetchAttach()
            } else {
              that.$message.warning('加载文件列表出错:', res.message)
            }
          })
        },
      })
    },
    showAttach(record) {
      var id = record.id
      var fileName = record.fileName
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.$emit('afterDown', [record])
        this.doDownLoadBatch(id)
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
    doDownLoadBatch(attachIds, ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      let tempFileName = null
      if (this.zipFileName) {
        tempFileName = this.zipFileName + '.zip'
      } else {
        tempFileName = new Date().valueOf() + '.zip'
      }
      var href =
        this.API_BASE_URL +
        this.urls.downLoadBatchWithFileName +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=' +
        ftpKey +
        '&token=' +
        this.$ls.get(ACCESS_TOKEN) +
        '&zipFileName=' +
        encodeURIComponent(tempFileName)
      iframe.src = href
      this.$emit('afterDown', this.selectedRows)
    },
  },
  watch: {
    _busKey: {
      handler(newV, oldV) {
        this.fetchAttach()
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>
<style>
.infoTips {
  background: #e6f7ff;
  border: 1px solid #aee1ff;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 14px;
  color: red;
}
</style>
